﻿using Microsoft.Extensions.Options;
using static System.Net.Mime.MediaTypeNames;

namespace FileManage;

public class ThumbnailMiddleware : IMiddleware
{
    UploadServerConfig _config;

    public ThumbnailMiddleware(IOptions<UploadServerConfig> config)
    {
        _config = config.Value;
    }

    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        if (context.Request.Query.ContainsKey("w") || context.Request.Query.ContainsKey("h"))
        {
            var appName = "";
            if (string.IsNullOrEmpty(_config.VirtualPath))
            {
                appName = context.Request.Path.Value.Split("/", StringSplitOptions.RemoveEmptyEntries)[0];
            }
            else
            {
                appName = context.Request.Path.Value.Replace(_config.VirtualPath, "")
                    .Split("/", StringSplitOptions.RemoveEmptyEntries)[0];
            }

            var appConfig = _config.GetAppConfig(appName);

            if (appConfig.EnableThumbnail != true)
            {
                return next.Invoke(context);
            }

            var ext = Path.GetExtension(context.Request.Path);
            //不能处理缩略图
            if (!appConfig.ThumbnailExts.Contains(ext))
            {
                return next.Invoke(context);
            }

            var w = int.Parse(context.Request.Query["w"].FirstOrDefault() ?? "0");
            var h = int.Parse(context.Request.Query["h"].FirstOrDefault() ?? "0");

            var filePath = context.Request.Path.Value.Replace(_config.VirtualPath, _config.PhysicalPath);
            var addStr = "." + w + "_" + h + ext;
            var newPath = filePath + addStr;
            ////修改Path
            context.Request.Path = context.Request.Path + addStr;
            context.Request.QueryString = new QueryString("");

            //缩略图存在
            if (File.Exists(newPath))
            {
                return next.Invoke(context);
            }

            //源文件不存在
            if (!File.Exists(filePath))
            {
                context.Response.StatusCode = 404;
                return Task.CompletedTask;
            }

            using (var image = Image.FromFile(filePath))
            {
                using (var thumb = image.GetThumbnailImage(w, h))
                {
                    thumb.Save(newPath, ImageFormat.Jpeg);
                }
            }

            return next.Invoke(context);
        }
        else
        {
            return next.Invoke(context);
        }
    }
}
